<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
           <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                    <el-row>
                        <!-- 资产提供方名称 -->
                        <el-col :span="5">
                            <el-form-item :label="$t('AssetsProviderManage.queryLabel.providerName')"   :label-width="queryformLabelWidthLong">
                                <el-input v-model.trim="formQueryCondition.providerName.val" class="queryItemStyle" clearable
                                        :placeholder="$t('AssetsProviderManage.queryLabel.placeholderProviderName')">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 状态 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('AssetsProviderManage.queryLabel.status')"  :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.isEnable.val" class="queryItemStyle" >
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                                    <!-- <el-option :label="$t('label.available')" value="Available"></el-option>
                                    <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 列表上的按钮 -->
                    <el-row>
                        <el-col :span="24">
                            <div style="text-align:right">
                                <el-form-item>
                                    <!-- 新增 -->
                                    <el-button v-permission="{menuCode: menuCode,resourceCode: 'saveBtnText'}"
                                    type="primary" v-if="test('onNewBtn')"
                                    @click="onNew('saveBtnText')">{{ $t('btnText.newBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 重置 -->
                                    <el-button v-permission="{menuCode: menuCode,resourceCode: 'resetBtnText'}" type="primary" @click="onReset('form')">{{ $t('btnText.resetBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item>
                                    <el-button type="primary" @click="onExport" icon="el-icon-download" :loading="loading">{{ $t('btnText.exportBtnText') }}</el-button>
                                </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 查询 -->
                                    <el-button v-permission="{menuCode: menuCode,resourceCode: 'queryBtnText'}" type="primary" @click="onQuery('queryBtnText')" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="dataBox" ref="dataBox">

                <transition enter-active-class="animated zoomIn" leave-active-class="animated rotateOut">
                    <el-table v-if="isInit" ref="singleTable"
                                :data="tableData"
                                :height="tableHeight"
                                @sort-change="sortChange"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                        <el-table-column type="index"  width="50" fixed="left"
                                            :label="$t('table.xh')" align="center">
                        </el-table-column>
                        <el-table-column :label="$t('table.op')" fixed="left" min-width="260">
                            <template slot-scope="scope">
                                <!--编辑-->
                                <el-button v-permission="{menuCode: menuCode,resourceCode: 'editBtnText'}"
                                 size="gv" icon="el-icon-edit" :loading="loading"
                                @click="edit(scope.$index, scope.row,'editBtnText')"
                                            >{{ $t('btnText.editBtnText') }}</el-button>
                                <!--下发-->
                                <el-button size="gv" icon="el-icon-delete"
                                    v-permission="{menuCode: menuCode, resourceCode: 'sendBtnText'}"
                                        type="danger" :loading="loading" @click="onSend(scope.$index, scope.row,'sendBtnText')"
                                       :disabled="scope.row.sendtoState!='StayDown'" >{{ $t('ParentAssetIssuance.btnText.sendBtnText') }}</el-button>
                                <!-- 注销 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Available'" v-permission="{menuCode: menuCode,resourceCode: 'passBtnText'}"
                                      type="danger" :loading="loading" @click="logoffRow(scope.$index, scope.row,'passBtnText')"
                                     >{{ $t('btnText.logoffBtnText') }}</el-button>
                                <!-- 恢复 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable==='Invalid'"
                                v-permission="{menuCode: menuCode,resourceCode: 'recoveryBtnText'}"
                                      type="danger" :loading="loading" @click="revertLogoffRow(scope.$index, scope.row,'recoveryBtnText')"
                                     >{{ $t('btnText.recoveryBtnText') }}</el-button>
                                <!-- 删除 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable==='Invalid' && scope.row.sendtoState !='StayDown'"
                                v-permission="{menuCode: menuCode,resourceCode: 'delBtnText'}"
                                      type="danger" :loading="loading" @click="deleteRow(scope.$index, scope.row,'delBtnText')"
                                     >{{ $t('btnText.deleteBtnText') }}</el-button>

                            </template>
                        </el-table-column>
                        <el-table-column prop="providerCode" min-width="140" fixed="left"
                                            :label="$t('AssetsProviderManage.table.providerCode')" sortable="custom" sort-by="providerCode">
                        </el-table-column>
                        <el-table-column prop="providerName" min-width="140" fixed="left"
                                            :label="$t('AssetsProviderManage.table.providerName')" sortable="custom" sort-by="providerName">
                        </el-table-column>
                        <!--所属专区-->
                        <el-table-column prop="speArea.speAreaName" min-width="140" fixed="left"
                                            :label="$t('AssetsProviderManage.table.speAreaName')" sortable="custom" sort-by="speArea.speAreaName">
                        </el-table-column>
                         <!--下发状态-->
                        <el-table-column prop="sendtoStateName" min-width="110"
                                            :label="$t('ParentAssetIssuance.table.ParentAssetIssuance.status')" sortable="custom" sort-by="sendtoState">
                        </el-table-column>
                        <el-table-column prop="providerContact" min-width="140"
                        :label="$t('AssetsProviderManage.table.providerTelephone')" sortable="custom" sort-by="providerContact">
                        </el-table-column>
                        <el-table-column prop="comAddress" min-width="150"
                        :label="$t('AssetsProviderManage.table.address')" sortable="custom" sort-by="comAddress">
                        </el-table-column>
                        <el-table-column prop="isEnableName" min-width="110" sortable="custom"
                        :label="$t('AssetsProviderManage.table.status')" sort-by="isEnable">
                        </el-table-column>

                        <el-table-column :label="$t('AssetsProviderManage.table.lastUpdatedBy')" min-width="120" sortable="custom" prop="modifier" sort-by="modifier">
                        </el-table-column>
                        <el-table-column :label="$t('AssetsProviderManage.table.lastUpdateTime')" min-width="180" sortable="custom" prop="lastUpdatedDate" sort-by="lastUpdatedDate">
                        </el-table-column>

                    </el-table>
                </transition>

            </div>
        </div>
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>

         <!--编辑对话框-->
        <transition enter-active-class="animated rotateIn" leave-active-class="animated rotateOut">
            <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowEditForm" top="5vh" :close-on-click-modal="false">
                <el-form :model="editForm" ref="editForm" size="mini"
                        :label-position="editFormPosition" status-icon=status-icon :rules="editRules">
                        <el-input v-model.trim="editForm.keyId"  v-show="false"></el-input>
                    <el-form-item :label="$t('AssetsProviderManage.editLabel.providerCode')"
                        :label-width="editformLabelWidth" prop="providerCode">
                        <el-input v-model.trim="editForm.providerCode" maxlength="20" :disabled="canEditCode"
                                :placeholder="$t('AssetsProviderManage.editLabel.placeholderProviderCode')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('AssetsProviderManage.editLabel.providerName')"
                        :label-width="editformLabelWidth" prop="providerName">
                        <el-input v-model.trim="editForm.providerName" maxlength="50"
                                :placeholder="$t('AssetsProviderManage.rules.placeholderProviderName')"></el-input>
                    </el-form-item>
                    <!--所属专区-->
                    <el-form-item :label="$t('shellAssets.editLabel.shellAssets.source')" :label-width="editformLabelWidth" prop="speAreaId">
                        <el-select v-model="editForm.speAreaId">
                            <el-option :value="drug.keyId" :key="drug.keyId" :label="drug.speAreaName"
                                    v-for="drug in source"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="$t('AssetsProviderManage.editLabel.providerTelephone')"
                        :label-width="editformLabelWidth" prop="providerContact">
                        <el-input v-model.trim="editForm.providerContact" maxlength="50"
                                :placeholder="$t('AssetsProviderManage.editLabel.placeholderProviderTelephone')"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('AssetsProviderManage.editLabel.address')"
                        :label-width="editformLabelWidth" prop="comAddress">
                        <el-input v-model="editForm.comAddress" maxlength="100" type="textarea"
                                :placeholder="$t('AssetsProviderManage.editLabel.placeholderAddress')"></el-input>
                    </el-form-item>

                     <el-form-item :label="$t('AssetsProviderManage.editLabel.status')"
                        :label-width="editformLabelWidth" prop="isEnable">
                        <el-select v-model="editForm.isEnable" class="queryItemStyle">
                            <el-option :label="$t('label.available')" value="Available"></el-option>
                            <el-option :label="$t('label.invalid')" value="Invalid"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button size="mini" @click="isShowEditForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                    <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
                </div>
            </el-dialog>
        </transition>

  </div>


</template>

<script>

import comBaseVue from '../../baseViewModel';

export default {
  mixins: [comBaseVue],
  name:'AssetsProviderManage',
  props: {
    menuCode: String
  },
  data () {
    return {
        queryformLabelWidthLong:"110px",
        isInit:false,
        isShowEditForm2: false,
        tableHeight:100,
        enables: [],
        singleSend:{},
        siteData:[],
        source: [],
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
        modelName:"com.ispr.iptv.entity.sys.SysProvider",
        // 查询条件
        formQueryCondition: {
            providerName: {
                key: 'providerName',
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            isEnable: {
                key: 'isEnable',
                op: '=', // 操作符
                val: ''
            },
        },

        // 编辑面板绑定的对象
        editForm: {
            keyId: 0,
            version: 0,
            providerCode: "",
            providerName: "",
            speAreaId: "",
            sendtoState: "",
            providerContact: "",
            comAddress: "",
            isEnable: "",
            // isAdd: "",
        },
        // 编辑面板的验证规则
        editRules: {
            providerCode: [{ required: true, message: this.$i18n.t('AssetsProviderManage.rules.placeholderProviderCode'), trigger: 'blur' }],
            providerName: [{ required: true, message: this.$i18n.t('AssetsProviderManage.rules.placeholderProviderName'), trigger: 'blur' }],
            // providerTelephone: [{ required: true, message: this.$i18n.t('AssetsProviderManage.rules.placeholderProviderTelephone'), trigger: 'blur' }],
            // address: [{ required: true, message: this.$i18n.t('AssetsProviderManage.rules.placeholderAddress'), trigger: 'blur' }]
        },
        //下发
        sendForm: {
            siteList: [],//下发到的站点
            sendType:"",
        },
        sendRules: {
            siteList: [{ required: true, message: this.$i18n.t('ParentAssetIssuance.rules.sendCheckTip'), trigger: 'blur' }],
        },
    }
  },
  methods:{
      test:function(btnCode){
          return true;
        },
     //单个下发
    onSend: function(index, row, rescode) {
        var _this = this;
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.sendForm.sendType = "single";
        this.singleSend = {};
        let data = {
          "keyId":row.keyId,
          "version":row.version,
          "resType":"PROVIDER",
        };
        let dataList = [];//最终传给后台的总数据
        dataList.push(data);
        this.$confirm(this.$i18n.t("message.confirmSendMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    _this.loading = true;
                    _this.procCommand("MediaSendToProc",
                    _this.modelName,
                    "Default",
                    {
                      "dataList":dataList,
                    },
                    null,
                    _this.submitFormCallback);
                }
            }
        });
    },
    // 新增
    onNew: function(rescode) {
          this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.providerCode = "";
        this.editForm.providerName = "";
        this.editForm.speAreaId = "";
        this.editForm.sendtoState = "StayDown";
        this.editForm.comAddress = "";
        this.editForm.providerContact = "";
        this.editForm.isEnable = "Available";
        // this.editForm.isAdd = "0";
        // this.editForm.isEnabled = "Available";
        this.curCommand = "MaterialProviderProc";
        this.canEditCode = false;
    },
    // 提交编辑面板数据
        submitForm: function submitForm(formName, rescode){
            this.currentResCode = (rescode && rescode!=='') ? rescode : '';
            var _this = this;
            this.setEditFormCheck();

            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    _this.loading = true;
                    _this.procCommand(_this.curCommand,
                    _this.modelName,
                    "Default",
                    _this.editForm,
                    _this.editFormCheck,
                    _this.submitFormCallback);
                } else {
                    return false;
                }
            });
        },
    //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck:function setEditFormCheck(){
        if(this.curCommand == "MaterialProviderProc"){
            this.editFormCheck = [{
                    key: 'providerCode',
                    op: '=', // 操作符
                    val: this.editForm.providerCode,// 查询的值
                    group:'provider'
                },
                // {
                //   key:'providerName',
                //   op:'=',
                //   val: this.editForm.providerName,
                //   group:'provider'
                // }
                ];
        }else if(this.curCommand == "MaterialProviderProcEdit"){
            this.editFormCheck = [{
                    key: 'providerCode',
                    op: '=', // 操作符
                    val: this.editForm.providerCode// 查询的值
                },
                {
                    key: 'keyId',
                    op: '<>', // 操作符
                    val: this.editForm.keyId
                },
                // {
                //   key:'providerName',
                //   op:'=',
                //   val: this.editForm.providerName
                // }
                ];
        }

    },
     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.providerName.val = "";
        this.formQueryCondition.isEnable.val = "Available";
    },


    // 授权按钮单击事件
    editMenu: function(index, row) {

    },

    // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
        if(isSuccess){
            this.curCommand = "MaterialProviderProcEdit";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            //this.editForm = json;
            this.canEditCode = true;
            this.editForm.keyId = json.keyId;
            this.editForm.providerCode = json.providerCode;
            this.editForm.providerName = json.providerName;
            this.editForm.speAreaId = json.speAreaId;
            this.editForm.providerContact = json.providerContact;
            this.editForm.comAddress = json.comAddress;
            this.editForm.sendtoState = "StayDown";
            this.editForm.isEnable = json.isEnable;
            this.editForm.version = json.version;
            // this.editForm.isAdd = "1";
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },

    // 注销按钮
        logoffRow: function(index, row, rescode) {
            this.currentResCode = (rescode && rescode!=='') ? rescode : '';
            var _this = this;
            this.$confirm(this.$i18n.t("message.confirmlogoffMessage"),
                this.$i18n.t("message.confirmTitle"), {
                confirmButtonText: this.$i18n.t("message.yes"),
                cancelButtonText: this.$i18n.t("message.cancel"),
                type: "warning",
                callback: function (action, instance) {
                    if (action == "confirm") {
                        var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Invalid", sendtoState:"StayDown" };
                        _this.loading = true;
                        _this.procCommand("PassProc",
                                _this.modelName,
                                "N",
                                commandBody,
                                null,
                                _this.submitFormCallback);
                    }

                }
            });
        },
        // 恢复注销按钮
        revertLogoffRow: function(index, row, rescode) {
            this.currentResCode = (rescode && rescode!=='') ? rescode : '';
            var _this = this;
            this.$confirm(this.$i18n.t("message.confirmNormalMessage"),
                this.$i18n.t("message.confirmTitle"), {
                confirmButtonText: this.$i18n.t("message.yes"),
                cancelButtonText: this.$i18n.t("message.cancel"),
                type: "warning",
                callback: function (action, instance) {
                    if (action == "confirm") {
                        var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Available", sendtoState:"StayDown" };
                        _this.loading = true;
                        _this.procCommand("RecoveryProc",
                                _this.modelName,
                                "N",
                                commandBody,
                                null,
                                _this.submitFormCallback);
                    }

                }
            });
        },


    // 为状态下拉框赋值
    findEnables: function() {
        this.findByTypeCode("10001",this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function(isSuccess,json) {
        try{
            if (isSuccess) {
                this.enables = [];
                for (var i = 0; i < json.data.length; i++) {
                    this.enables.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },
     //站点复选框数据 siteData
    findSite: function(){
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.Site",//修改为被查询的实体地址
                opKey: "Query",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{key: 'isEnable',op: '=',val: 'Available'}],
                userInfo: this.getUserInfo()
            };
            var _this = this;
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        _this.siteData = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.siteData.push(res.data.data[i]);
                        }
                    } else {
                        // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                });
    },

    // 为资产来源下拉框赋值
    findSource:function(){
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.SpeArea",//修改为被查询的实体地址
                opKey: "SpeArea",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{key: 'isEnable',op: '=',val: 'Available'}],
                userInfo: this.getUserInfo()
            };
            var _this = this;
            this.axios.post('/api/speArea/query', queryRequest, {headers: this.headersObj})//findAllValueType修改为query
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        _this.source = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.source.push(res.data.data[i]);
                        }
                    } else {
                        // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                });
    },

    refresh: function(){
        if (this.$refs['sendForm']) {
            this.$refs['sendForm'].resetFields();
        }
        this.sendForm.siteList = [];
    },
    initTable:function(){
        this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
        this.isInit = true;
    },
    enterDown(){
        var g = this
          if(g.isShowEditForm){
              g.submitForm('editForm',g.currentResCode)
          }else if(!g.loading){
              g.onQuery()
        }
    }
    


  },
  mounted: function mounted() {
    this.findSite();
    this.findSource();
    this.findEnables();
    this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    this.isInit = true;
    this.formQueryCondition.isEnable.val = "Available";
    this.onQuery();
    window.setTimeout(this.initTable,100);
  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
